//
//  UIView+Extend.m
//  SmallElephant
//
//  Created by dev on 2023/2/10.
//

#import "UIView+Extend.h"

@implementation UIView (Extend)

/// 添加子视图
- (void)addSubview:(UIView *)view style:(NSString*)style {
    [self addSubview:view style:style applyLayoutPreservingOrigin:NO];
}

/// 添加子视图
- (void)addSubview:(UIView *)view style:(NSString*)style applyLayoutPreservingOrigin:(BOOL)applyLayoutPreservingOrigin {
    [self addSubview:view];
    [view applyStyle:style applyLayoutPreservingOrigin:applyLayoutPreservingOrigin];
}

// 将样式字符解析成字典
- (NSDictionary*)parseStyle:(NSString*)style {
    NSMutableDictionary *attribute = [[NSMutableDictionary alloc] init];
    if(style!=nil) {
        NSArray *styleDatas = [style componentsSeparatedByString:@";"];
        for(int i=0;i<styleDatas.count;i++) {
            NSString *styleDataString = (NSString*)styleDatas[i];
            styleDataString = [styleDataString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            if(styleDataString.length!=0) {
                NSArray *styleDataItem = [styleDataString componentsSeparatedByString:@":"];
                NSString *key = (NSString*)styleDataItem[0];
                key = [key stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                NSString *value = (NSString*)styleDataItem[1];
                value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                attribute[key] = value;
            }
        }
    }
    return attribute;
}

/// 应用布局样式
- (void)applyStyle {
    [self applyStyle:@""];
}

/// 应用布局样式
- (void)applyStyle:(NSString*)style {
    [self applyStyle:style applyLayoutPreservingOrigin:YES];
}

/// 应用布局样式
- (void)applyStyle:(NSString*)styleData applyLayoutPreservingOrigin:(BOOL)applyLayoutPreservingOrigin {
    NSDictionary *style = [self parseStyle:styleData];
    // 设置背景色
    if(style[@"background"]) {
        NSString *background = style[@"background"];
        @try {
            if([background rangeOfString:@"url"].location!=NSNotFound) {
                // 背景图片
                background = [background substringFromIndex:4];
                background = [background substringToIndex:background.length - 1];
                NSString *path = [[NSBundle mainBundle] pathForResource:background ofType:@"png"];
                UIImage *image = [UIImage imageWithContentsOfFile:path];
                self.layer.contents = (id)image.CGImage;
            } else {
                self.backgroundColor = [UIColor colorWithHexString:background];
            }
        } @catch (NSException *exception) {
        } @finally {
        }
        
    }
    // 设置圆角
    if(style[@"border-radius"]) {
        self.layer.cornerRadius = [style[@"border-radius"] floatValue];
        self.layer.masksToBounds = YES;
    }
    // 设置边框大小
    if(style[@"border-width"]) {
        self.layer.borderWidth = [style[@"border-width"] floatValue];
    }
    // 设置边框颜色
    if(style[@"border-color"]) {
        self.layer.borderColor = [[UIColor colorWithHexString:style[@"border-color"]] CGColor];
    }
    // 设置文字颜色
    if(style[@"color"]) {
        if([self isKindOfClass:NSClassFromString(@"UILabel")]) {
            UILabel *label = (UILabel*)self;
            label.textColor = [UIColor colorWithHexString:style[@"color"]];
        } else if([self isKindOfClass:NSClassFromString(@"UIButton")]) {
            UIButton *button = (UIButton*)self;
            [button setTitleColor:[UIColor colorWithHexString:style[@"color"]] forState:UIControlStateNormal];
        } else if([self isKindOfClass:NSClassFromString(@"UITextField")]) {
            UITextField *textField = (UITextField*)self;
            [textField setTextColor:[UIColor colorWithHexString:style[@"color"]]];
        }
    }
    // 设置文字大小
    if(style[@"font-size"]) {
        UIFontWeight weight = UIFontWeightRegular;
        // 设置文字粗细
        if(style[@"font-weight"]) {
            if([style[@"font-weight"] isEqualToString:@"bold"]) {
                weight = UIFontWeightBold;
            } else if([style[@"font-weight"] isEqualToString:@"normal"]) {
                weight = UIFontWeightRegular;
            }
        }
        if([self isKindOfClass:NSClassFromString(@"UILabel")]) {
            UILabel *label = (UILabel*)self;
            label.font = [UIFont systemFontOfSize:FONT_SIZE([style[@"font-size"] floatValue]) weight:weight];
        } else if([self isKindOfClass:NSClassFromString(@"UIButton")]) {
            UIButton *button = (UIButton*)self;
            button.titleLabel.font = [UIFont systemFontOfSize:FONT_SIZE([style[@"font-size"] floatValue]) weight:weight];
        } else if([self isKindOfClass:NSClassFromString(@"UITextField")]) {
            UITextField *textField = (UITextField*)self;
            textField.font = [UIFont systemFontOfSize:FONT_SIZE([style[@"font-size"] floatValue]) weight:weight];
        }
    }
    
    // 设置文字对齐方向
    if(style[@"text-align"]) {
        if([self isKindOfClass:NSClassFromString(@"UILabel")]) {
            UILabel *label = (UILabel*)self;
            if([style[@"text-align"] isEqualToString:@"left"]) {
                label.textAlignment = NSTextAlignmentLeft;
            } else if([style[@"text-align"] isEqualToString:@"center"]) {
                label.textAlignment = NSTextAlignmentCenter;
            } else if([style[@"text-align"] isEqualToString:@"right"]) {
                label.textAlignment = NSTextAlignmentRight;
            } else if([style[@"text-align"] isEqualToString:@"left"]) {
                label.textAlignment = NSTextAlignmentLeft;
            }
        } else if([self isKindOfClass:NSClassFromString(@"UITextField")]) {
            UITextField *textField = (UITextField*)self;
            if([style[@"text-align"] isEqualToString:@"left"]) {
                textField.textAlignment = NSTextAlignmentLeft;
            } else if([style[@"text-align"] isEqualToString:@"center"]) {
                textField.textAlignment = NSTextAlignmentCenter;
            } else if([style[@"text-align"] isEqualToString:@"right"]) {
                textField.textAlignment = NSTextAlignmentRight;
            } else if([style[@"text-align"] isEqualToString:@"left"]) {
                textField.textAlignment = NSTextAlignmentLeft;
            }
        }
    }
    
    // 配置布局约束
    [self configureLayoutWithBlock:^(YGLayout * _Nonnull layout) {
        layout.isEnabled = YES;
        if(style[@"position"]) {
            if([style[@"position"] isEqualToString:@"absolute"]) {
                layout.position = YGPositionTypeAbsolute;
            }
        }
        if(style[@"left"]) {
            layout.left = YGPointValue([self getFloatValue:style[@"left"]]);
        }
        if(style[@"right"]) {
            layout.right = YGPointValue([self getFloatValue:style[@"right"]]);
        }
        if(style[@"top"]) {
            layout.top = YGPointValue([self getFloatValue:style[@"top"]]);
        }
        if(style[@"bottom"]) {
            layout.bottom = YGPointValue([self getFloatValue:style[@"bottom"]]);
        }
        
        if(style[@"display"]) {
            if([style[@"display"] isEqualToString:@"none"]) {
                layout.display = YGDisplayNone;
            } else if([style[@"display"] isEqualToString:@"flex"]) {
                layout.display = YGDisplayFlex;
            }
        }
        if(style[@"width"]) {
            if([style[@"width"] rangeOfString:@"%"].location!=NSNotFound) {
                layout.width = YGPercentValue([style[@"width"] intValue]);
            } else if([style[@"width"] rangeOfString:@"auto"].location!=NSNotFound) {
                layout.width = YGValueAuto;
            } else {
                layout.width = YGPointValue([self getFloatValue:style[@"width"]]);
            }
        }
        if(style[@"min-width"]) {
            if([style[@"min-width"] rangeOfString:@"%"].location!=NSNotFound) {
                layout.minWidth = YGPercentValue([style[@"min-width"] intValue]);
            } else if([style[@"min-width"] rangeOfString:@"auto"].location!=NSNotFound) {
                layout.minWidth = YGValueAuto;
            } else {
                layout.minWidth = YGPointValue(SIZE([style[@"min-width"] intValue]));
            }
        }
        if(style[@"max-width"]) {
            if([style[@"max-width"] rangeOfString:@"%"].location!=NSNotFound) {
                layout.maxWidth = YGPercentValue([style[@"max-width"] intValue]);
            } else if([style[@"max-width"] rangeOfString:@"auto"].location!=NSNotFound) {
                layout.maxWidth = YGValueAuto;
            } else {
                layout.maxWidth = YGPointValue(SIZE([style[@"max-width"] intValue]));
            }
        }
        if(style[@"height"]) {
            if([style[@"height"] rangeOfString:@"%"].location!=NSNotFound) {
                layout.height = YGPercentValue([style[@"height"] intValue]);
            } else if([style[@"height"] rangeOfString:@"auto"].location!=NSNotFound) {
                layout.height = YGValueAuto;
            } else {
                layout.height = YGPointValue([self getFloatValue:style[@"height"]]);
            }
        }
        if(style[@"min-height"]) {
            if([style[@"min-height"] rangeOfString:@"%"].location!=NSNotFound) {
                layout.minHeight = YGPercentValue([style[@"min-height"] intValue]);
            } else if([style[@"min-height"] rangeOfString:@"auto"].location!=NSNotFound) {
                layout.minHeight = YGValueAuto;
            } else {
                layout.minHeight = YGPointValue(SIZE([style[@"min-height"] intValue]));
            }
        }
        if(style[@"max-height"]) {
            if([style[@"max-height"] rangeOfString:@"%"].location!=NSNotFound) {
                layout.maxHeight = YGPercentValue([style[@"max-height"] intValue]);
            } else if([style[@"max-height"] rangeOfString:@"auto"].location!=NSNotFound) {
                layout.maxHeight = YGValueAuto;
            } else {
                layout.maxHeight = YGPointValue(SIZE([style[@"max-height"] intValue]));
            }
        }
        if(style[@"padding"]) {
            layout.padding = YGPointValue([self getFloatValue:style[@"padding"]]);
        }
        if(style[@"padding-top"]) {
            layout.paddingTop = YGPointValue([self getFloatValue:style[@"padding-top"]]);
        }
        if(style[@"padding-left"]) {
            layout.paddingLeft = YGPointValue([self getFloatValue:style[@"padding-left"]]);
        }
        if(style[@"padding-right"]) {
            layout.paddingRight = YGPointValue([self getFloatValue:style[@"padding-right"]]);
        }
        if(style[@"padding-bottom"]) {
            layout.paddingBottom = YGPointValue([self getFloatValue:style[@"padding-bottom"]]);
        }
        
        if(style[@"margin"]) {
            layout.margin = YGPointValue([self getFloatValue:style[@"margin"]]);
        }
        if(style[@"margin-top"]) {
            layout.marginTop = YGPointValue([self getFloatValue:style[@"margin-top"]]);
        }
        if(style[@"margin-left"]) {
            layout.marginLeft = YGPointValue([self getFloatValue:style[@"margin-left"]]);
        }
        if(style[@"margin-right"]) {
            layout.marginRight = YGPointValue([self getFloatValue:style[@"margin-right"]]);
        }
        if(style[@"margin-bottom"]) {
            layout.marginBottom = YGPointValue([self getFloatValue:style[@"margin-bottom"]]);
        }
        if(style[@"flex-direction"]) {
            if([style[@"flex-direction"] isEqualToString:@"row"]) {
                layout.flexDirection = YGFlexDirectionRow;
            } else if([style[@"flex-direction"] isEqualToString:@"row-reverse"]) {
                layout.flexDirection = YGFlexDirectionRowReverse;
            } else if([style[@"flex-direction"] isEqualToString:@"column"]) {
                layout.flexDirection = YGFlexDirectionColumn;
            } else if([style[@"flex-direction"] isEqualToString:@"column-reverse"]) {
                layout.flexDirection = YGFlexDirectionColumnReverse;
            }
        }
        
        if(style[@"flex-wrap"]) {
            if([style[@"flex-wrap"] isEqualToString:@"nowrap"]) {
                layout.flexWrap = YGWrapNoWrap;
            } else if([style[@"flex-wrap"] isEqualToString:@"wrap"]) {
                layout.flexWrap = YGWrapWrap;
            } else if([style[@"flex-wrap"] isEqualToString:@"wrap-reverse"]) {
                layout.flexWrap = YGWrapWrapReverse;
            }
        }
        
        if(style[@"justify-content"]) {
            if([style[@"justify-content"] isEqualToString:@"flex-start"]) {
                layout.justifyContent = YGJustifyFlexStart;
            } else if([style[@"justify-content"] isEqualToString:@"flex-end"]) {
                layout.justifyContent = YGJustifyFlexEnd;
            } else if([style[@"justify-content"] isEqualToString:@"center"]) {
                layout.justifyContent = YGJustifyCenter;
            } else if([style[@"justify-content"] isEqualToString:@"space-between"]) {
                layout.justifyContent = YGJustifySpaceBetween;
            } else if([style[@"justify-content"] isEqualToString:@"space-around"]) {
                layout.justifyContent = YGJustifySpaceAround;
            }
        }
        
        if(style[@"align-items"]) {
            if([style[@"align-items"] isEqualToString:@"flex-start"]) {
                layout.alignItems = YGAlignFlexStart;
            } else if([style[@"align-items"] isEqualToString:@"flex-end"]) {
                layout.alignItems = YGAlignFlexEnd;
            } else if([style[@"align-items"] isEqualToString:@"center"]) {
                layout.alignItems = YGAlignCenter;
            } else if([style[@"align-items"] isEqualToString:@"baseline"]) {
                layout.alignItems = YGAlignBaseline;
            } else if([style[@"align-items"] isEqualToString:@"stretch"]) {
                layout.alignItems = YGAlignStretch;
            }
        }
        
        if(style[@"align-content"]) {
            if([style[@"align-content"] isEqualToString:@"flex-start"]) {
                layout.alignContent = YGAlignFlexStart;
            } else if([style[@"align-content"] isEqualToString:@"flex-end"]) {
                layout.alignContent = YGAlignFlexEnd;
            } else if([style[@"align-content"] isEqualToString:@"center"]) {
                layout.alignContent = YGAlignCenter;
            } else if([style[@"align-content"] isEqualToString:@"space-between"]) {
                layout.alignContent = YGAlignSpaceBetween;
            } else if([style[@"align-content"] isEqualToString:@"space-around"]) {
                layout.alignContent = YGAlignSpaceAround;
            } else if([style[@"align-content"] isEqualToString:@"stretch"]) {
                layout.alignContent = YGAlignStretch;
            }
        }
        
        // 项目属性设置
        if(style[@"flex-grow"]) {
            layout.flexGrow = [style[@"flex-grow"] floatValue];
        }
        if(style[@"flex-shrink"]) {
            layout.flexShrink = [style[@"flex-shrink"] floatValue];
        }
        if(style[@"align-self"]) {
            if([style[@"align-self"] isEqualToString:@"auto"]) {
                layout.alignSelf = YGAlignAuto;
            } else if([style[@"align-self"] isEqualToString:@"flex-end"]) {
                layout.alignSelf = YGAlignFlexEnd;
            } else if([style[@"align-self"] isEqualToString:@"center"]) {
                layout.alignSelf = YGAlignCenter;
            } else if([style[@"align-self"] isEqualToString:@"baseline"]) {
                layout.alignSelf = YGAlignBaseline;
            } else if([style[@"align-self"] isEqualToString:@"stretch"]) {
                layout.alignSelf = YGAlignStretch;
            }
        }
        
        if(style[@"flex"]) {
            layout.flex = [style[@"flex"] floatValue];
        }
    }];
}

- (CGFloat)getFloatValue:(NSString*)value {
    if([value isEqualToString:@"--safe-area-top"]) {
        return [UIDevice vg_safeDistanceTop];
    } else if([value isEqualToString:@"--safe-area-bottom"]) {
        return [UIDevice vg_safeDistanceBottom];
    } else if([value isEqualToString:@"--tabbar-full-height"]) {
        return [UIDevice vg_tabBarFullHeight];
    } else if([value isEqualToString:@"--status-bar-height"]) {
        return [UIDevice vg_statusBarHeight];
    } else if([value isEqualToString:@"--tabbar-height"]) {
        return [UIDevice vg_tabBarHeight];
    }
    return [value floatValue];
}

- (NavigationController*)getRootController {
    NavigationController *rootController = nil;
    // 从当前视图开始遍历响应者链条
    UIResponder *nextResponder = self.nextResponder;
    while (nextResponder) {
        if ([nextResponder isKindOfClass:[NavigationController class]]) {
            rootController = (NavigationController*)nextResponder;
        }
        // 继续沿着响应者链条向上查找
        nextResponder = nextResponder.nextResponder;
    }
    return rootController;
}

@end
